package com.quectel.core.module.grid.service.impl;

import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.grid.dao.GridPlanDao;
import com.quectel.core.module.grid.dao.GridPlanGridBindingDao;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridPlanDto;
import com.quectel.core.module.grid.dto.GridPlanGridBindingDto;
import com.quectel.core.module.grid.entity.GridPlanEntity;
import com.quectel.core.module.grid.entity.GridPlanGridBindingEntity;
import com.quectel.core.module.grid.service.GridPlanGridBindingService;
import com.quectel.core.module.grid.service.GridPlanService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@DubboService
public class GridPlanServiceImpl implements GridPlanService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridPlanServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> GRID_PLAN_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "GRID_PLAN_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<GridPlanDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(GRID_PLAN_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private GridPlanDao gridPlanDao;
    @Autowired
    private GridService gridService;
    @Autowired
    private GridPlanGridBindingService gridPlanGridBindingService;
    @Autowired
    private GridPlanGridBindingDao gridPlanGridBindingDao;

    /**
     * 先删除绑定资源 再新增
     *
     * @param gridPlanDto
     */
    @Override
    public void saveOrUpdate(GridPlanDto gridPlanDto) {
        if (gridPlanDto.getId() == null) {
            Long id = save(gridPlanDto);
            gridPlanDto.setId(id);
        } else {
            updateById(gridPlanDto);
        }

        //删除关联关系
        gridPlanGridBindingDao.delete(new LambdaQueryWrapper<GridPlanGridBindingEntity>()
                .eq(GridPlanGridBindingEntity::getPlanId, gridPlanDto.getId()));

        List<Long> bindGrid = gridPlanDto.getBindGrid();
        for (Long gridId : bindGrid) {
            GridPlanGridBindingEntity entity = new GridPlanGridBindingEntity();
            entity.setId(Snowflake.nextId());
            entity.setPlanId(gridPlanDto.getId());
            entity.setGridId(gridId);
            gridPlanGridBindingDao.insert(entity);
        }
    }

    @Override
    public GridPlanDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                GRID_PLAN_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public GridPlanDto selectById(Long id) {
        GridPlanEntity entity = gridPlanDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, GridPlanDto.class));
    }

    @Override
    public List<GridPlanDto> queryList(Map<String, Object> params) {
        List<GridPlanEntity> list = gridPlanDao.queryList(params);
        List<GridPlanDto> result = CopyUtils.copyList(list, GridPlanDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private GridPlanDto paddingField(GridPlanDto dto) {
        if (dto != null) {
            List<GridDto> gridList = new ArrayList<>();
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put(LambdaUtil.getFieldName(GridPlanGridBindingDto::getPlanId), dto.getId());
            List<GridPlanGridBindingDto> gridPlanGridBindingDtos = gridPlanGridBindingService.queryList(queryMap);
            if (CollectionUtils.isNotEmpty(gridPlanGridBindingDtos)) {
                for (GridPlanGridBindingDto bind : gridPlanGridBindingDtos) {
                    Long gridId = bind.getGridId();
                    GridDto gridDto = gridService.selectCacheById(gridId);
                    gridList.add(gridDto);
                }
                dto.setGridList(gridList);
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return gridPlanDao.queryTotal(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(GridPlanDto dto) {
        GridPlanEntity entity = CopyUtils.copyObj(dto, GridPlanEntity.class);
        entity.setId(Snowflake.nextId());
        gridPlanDao.insert(entity);
        List<Long> bindGrid = dto.getBindGrid();
        for (Long gridId : bindGrid) {
            GridPlanGridBindingDto addly = new GridPlanGridBindingDto();
            addly.setPlanId(entity.getId());
            addly.setGridId(gridId);
            gridPlanGridBindingService.save(addly);
        }
        return entity.getId();
    }

    @Override
    public void updateById(GridPlanDto dto) {
        GridPlanEntity entity = CopyUtils.copyObj(dto, GridPlanEntity.class);

        gridPlanDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(GridPlanDto dto) {
        GridPlanEntity entity = CopyUtils.copyObj(dto, GridPlanEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, gridPlanDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        gridPlanDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
